package controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.Role;
import service.RoleService;
import utils.Page;

import java.util.List;

@Controller                                    //Spring帮助实例化对象
@RequestMapping("/role")                    // 相当于  @WebServlet(urlPatterns = "/user")
public class RoleController {
    //5个if判断(根据传的参数区分) 写成方法 方法加路径绑定 地址里面可以直接接

    @Autowired
    private RoleService roleService;

    @RequestMapping("/login")
    public String login(Role role){
        //登录逻辑 方法上写参数可以自动获取参数  name的值和user类中属性一致 参数自动映射过来

        boolean flag=roleService.login(role);
        if(flag){
            return "index";
        }else{
            return "login";
        }
    }
    @RequestMapping("/list/{currentPage}")
    public String list(Role role, @PathVariable("currentPage") Integer currentPage, Model model){
        //查数据
        Page page=new Page();
        int totalCount = roleService.count(role);
        page.setTotalCount(totalCount);
        page.setCurrentPage(currentPage);
        page.setTotalPage();

        //计算偏移量
        int offset= (currentPage-1)*page.getPageSize();
        List<Role> roles = roleService.findAll(role,offset,page.getPageSize());

        model.addAttribute("roles",roles);
        model.addAttribute("page",page);
        model.addAttribute("role",role);

        return "role/list";
    }

    @RequestMapping("/toadd")
    public String toAdd(){
        //直接打开 转发
        return "role/add";
    }
    @RequestMapping("/addSave")
    public String addSave(Role role){
        int result = roleService.addRole(role.getRname());
        if(result>0){
            //类似重定向
            return "redirect:/role/list/1";
        }else{
            return "error";
        }
    }
    @RequestMapping("/delete/{id}")
    public String deleteById(@PathVariable("id")Integer id){
        int result = roleService.deleteRoleById(id);
        if(result>0){
            return "redirect:/role/list/1";
        }else{
            return "error";
        }
    }
    @RequestMapping("/toupdate/{id}")
    public String toupdate(@PathVariable("id")Integer id,Model model){
        Role role = roleService.findById(id);
        model.addAttribute("role",role);
        return "role/update";
    }

    @RequestMapping("/updateSave")
    public String updateSave(Role role){
        int result=roleService.updateRole(role);
        if(result>0){
            return "redirect:/role/list/1";
        }else{
            return "error";
        }
    }

}
